﻿using UnityEngine;
using System.Linq;
using ETModel;
using System.Collections.Generic;

namespace ETModel {
    /// <summary>
    /// 自由视察指定对象,附加给摄像机
    /// </summary>
    public class FreeViewGameObject : MonoBehaviour {
        public GameObject ViewGameObject;
        public float Distance = 2;
        /// <summary>
        /// 鼠标旋转灵敏度,越大越灵敏
        /// </summary>
        public float RotateSpeed = 5.0f;

        /// <summary>
        /// 相机跟随单位的偏移量,默认是zero
        /// </summary>
        private Vector3 followOffset;
        private float MainCameraAnglesX = 0;
        private float MainCameraAnglesY = 0;
        private float MainCameraAnglesZ = -4;

        private Vector3 mousePos;

        private void Start() {
            if (ViewGameObject == null) {
                throw new System.Exception("ViewGameObject需要设置");
            }
            followOffset = gameObject.transform.position - ViewGameObject.transform.position;
            Vector3 angles = gameObject.transform.eulerAngles;
            MainCameraAnglesX = angles.y;
            MainCameraAnglesY = angles.x;
            MainCameraAnglesZ = angles.z;


            gameObject.transform.LookAt(ViewGameObject.transform.position);
        }

        private void LateUpdate() {
            if (ViewGameObject == null) return;
            var prevMousePos = mousePos;
            mousePos = Input.mousePosition;
            if (Input.GetMouseButton(0)) {
                //左键按住开始旋转摄像头
                var mX = mousePos.x - prevMousePos.x;
                var mY = mousePos.y - prevMousePos.y;
                gameObject.transform.RotateAround(ViewGameObject.transform.position, Vector3.up, mX * Time.deltaTime * RotateSpeed);
                gameObject.transform.RotateAround(ViewGameObject.transform.position, gameObject.transform.right, -mY * Time.deltaTime * RotateSpeed);
            }
        }
    }
}
